import { useEffect, useLayoutEffect, useRef } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';

import styles from './index.module.scss';
/*
    需要已知父元素定高
*/
export default props => {
    const contRef = useRef(null);

    // 可能加载不满一屏，无法触发滚动
    useLayoutEffect(() => {
        const element = contRef.current;
        if (
            element?.firstChild &&
            element?.clientHeight >= element?.scrollHeight
        ) {
            const resizeObserver = new ResizeObserver((entries) => {
                if (entries[0].target.clientHeight <= element.clientHeight) {
                    element.dispatchEvent(new CustomEvent('scroll'));
                }
            });

            resizeObserver.observe(element.firstChild);
            return () => resizeObserver.disconnect();
        }
    }, [props.dataList]);

    return (
        <div className={styles['container']} style={{width:'100%',height:'100%',overflow:'auto'}} id="cont" ref={contRef}>
            <InfiniteScroll
                scrollableTarget={'cont'}
                loader={<div className={styles['loader']}>加载中......</div>}
                endMessage={props?.dataList?.length ? <div className={styles['line']}><span>这是我的底线</span></div> : null}
                {...props}
            />
        </div>
    )
}
